<?php

namespace App\Controller\Home;


use App\Controller\Example\NoticeExample;
use App\Controller\Example\UserExample;
use App\Models\BannerModel;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\CtcModel;
use App\Models\CtcSettingModel;
use App\Models\NationalityModel;
use App\Models\NoticeModel;
use App\Models\SettlementModel;
use App\Models\UsersModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Result\Result;

class Home
{
    /**
     * TODO 客户端获取轮播图
     * entry
     * return json
     * */
    public function banner($data)
    {
        Result::success(
            BannerModel::getBannerList(new Conn(), $data["position"])
        );
    }

    /**
     * TODO 客户端获取国籍
     * entry
     * return json
     * */
    public function languageList()
    {
        Result::success(NationalityModel::getNationalityList(new Conn()));
    }
    /**
     * TODO 获取交易积分价格
     * entry
     * return json
     * */
    public function getMoneyPrice()
    {
        Result::success(CtcSettingModel::getCtcSettingInit(new Conn(),2)["consult_price"]);
    }

    /**
     * TODO 首页轮播最新公告
     * entry
     * return json
     * */
    public function homeNotice()
    {

        $conn = new Conn();
        $newNotice = NoticeModel::getNewNotice($conn);
        $configSingle = ConfigModel::getConfigSingleValName($conn, Config::NOTICE_TIME);
        $newNotice["is_pop"] = strtotime($newNotice["time"]) + $configSingle > time();
        Result::success($newNotice);
    }

    /**
     * TODO 公告列表
     * entry page limit
     * return json
     * */
    public function noticeList($data)
    {
        $assemble = Common::identical($data);
        Result::success(NoticeModel::getNoticeList(new Conn(), $assemble));
    }

    /**
     * TODO 公告详情
     * entry id
     * return json
     * */
    public function noticeDetails($data)
    {
        $assemble = Common::assemble(new NoticeExample(), $data);
        Result::success(NoticeModel::getNoticeDetails(new Conn(), $assemble));
    }

    /**
     * TODO 产品分类
     * @return void
     */
    public function goodsCategory($data)
    {
        $type = $data['type'] ?? 1;
        $order = "order by sort desc,create_time desc";
        $field = 'category_id,category_pid,category_name,img_id';
        $where = "is_hide=0 and is_delete=0 and type=$type";
        $分类列表 = "select $field from `shop_category` where $where $order";
        $conn = new Conn();
        $分类列表 = $conn->readConn($分类列表, true);
        foreach ($分类列表 as $item=>$value){
            if($value[img_id] > 0){
                $分类列表[$item]["img"] = Common::fileUrl($conn->readConn("select `domain`,file_path from jj_file where file_id in($value[img_id])"));;
            }
        }
        $分类列表 = Common::list_to_tree($分类列表, 'category_id', 'category_pid');
        Result::success($分类列表);
    }

    /**
     * TODO 产品列表
     * entry page limit
     * return json
     * */
    public function goodsList($data)
    {
        $分类ID = $data["category_id"];
        $goods_type = $data["goods_type"] ?? 1;
        $name = $data["name"];
        $token = $data["token"];
        $where = 'is_delete=0 and is_adopt=1 and is_top=1 and goods_type='.$goods_type;
        if ($分类ID) {
            $where .= " and `category_id` = $分类ID";
        }
        if ($name) {
            $where .= " and `name` like '%$name%'";
        }
        $identical = Common::identical($data);
        $order = "order by sort desc,sell_price asc,unreal_sales_volume desc,sales_volume desc,create_time desc";
        $field = 'goods_id,nationality_id,category_id,merchant_id,name,goods_type,title,cost_price,old_price,sell_price,img_id,hits,sales_volume,unreal_sales_volume,create_time';
        $商品信息 = "select $field from shop_goods where $where $order limit $identical->pageStart,$identical->limit";
        $conn = new Conn();
        $商品信息 = $conn->readConn($商品信息, true);
        $文件ID = implode(',', array_column($商品信息, 'img_id', 'img_id'));
        $文件信息 = $conn->readConn("select file_id,storage,`domain`,file_path from jj_file where file_id in($文件ID)", true);
        foreach ($文件信息 as $k => $v) {
            $文件信息[$k]['file_url'] = Common::fileUrl($v);
        }
        $文件信息 = array_column($文件信息, 'file_url', 'file_id');

        foreach ($商品信息 as $k => $v) {
            $商品信息[$k]['img_url'] = $文件信息[$v['img_id']] ?? '';
            $商品信息[$k]['sales_volume'] += $v['unreal_sales_volume'];
            $商品信息[$k]['sell_price'] = $v["sell_price"];
        }
        $总数量 = "SELECT count(`goods_id`) as count FROM `shop_goods` WHERE $where";
        $ret["list"] = $商品信息;
        $ret["count"] = $conn->readConn($总数量)["count"];
        Result::success($ret);
    }

    /**
     * 商品详情
     * entry  gid
     * return json
     * */
    public function goodsDetails($data)
    {
        $assemble = Common::assemble(new UserExample(), $data);
        $商品ID = $data["goods_id"];
        $token = $data["token"];
        $conn = new Conn();
        $商品信息 = "select goods_id,merchant_id,nationality_id,category_id,goods_type,name,img_id,title,content,img_ids,imgs,cost_price,old_price,sell_price,hits,sales_volume,unreal_sales_volume,is_adopt,is_top,is_delete,(select sum(sku_stock) from shop_goods_sku where goods_id=$商品ID and is_delete=0) as stock from shop_goods where goods_id=$商品ID limit 1";
        $商品信息 = $conn->readConn($商品信息);
        if (!$商品信息) Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        if ($商品信息['is_adopt'] == 0) Result::error(ErrorEnum::PRODUCTINFORMATIONNOTAPPROVED[$assemble->language]);
        if ($商品信息['is_top'] == 0) Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        if ($商品信息['is_delete'] == 1) Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        $consult_price = CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"];
        $商品信息['sell_price'] = $商品信息["sell_price"];
        $商品信息['sales_volume'] += $商品信息['unreal_sales_volume'];
        $文件ID = empty($商品信息['img_ids']) ? $商品信息['img_id'] : "{$商品信息['img_id']},{$商品信息['img_ids']}";
        $文件信息 = $conn->readConn("select file_id,storage,`domain`,file_path from jj_file where file_id in($文件ID)",true);
        foreach ($文件信息 as $k => $v) {
            $文件信息[$k]['file_url'] = Common::fileUrl($v);
        }
        $文件信息 = array_column($文件信息, 'file_url', 'file_id');
        $商品信息['img_url'] = $文件信息[$商品信息['img_id']] ?? '';
        $图片数组信息 = [];
        foreach (explode(',',$商品信息['img_ids']) as $k=>$v){
            $图片数组信息[$k]['file_url'] = $文件信息[$v];
        }
        $商品信息['imgs'] = $图片数组信息;

        $商品SKU信息 = $conn->readConn("select sku_id,goods_id,spec_info from shop_goods_sku where goods_id=$商品ID and is_delete=0",true);
        $商品规格ID = [];
        foreach ($商品SKU信息 as $v) {
            $specArr = json_decode($v['spec_info']);
            foreach ($specArr as $kk => $vv) {
                $商品规格ID[] = $kk;
                $商品规格ID[] = $vv;
            }
        }
        $商品规格ID = implode(',', array_unique($商品规格ID));
        $商品规格信息 = "select spec_id,spec_pid,name from shop_goods_spec where spec_id in($商品规格ID) and is_delete=0";
        $商品规格信息 = $conn->readConn($商品规格信息,true);
        $商品规格信息 = Common::list_to_tree($商品规格信息, 'spec_id', 'spec_pid');
        $商品信息['spec'] = $商品规格信息;
        Result::success($商品信息);
    }

    /**
     * 商品SKU TODO
     * @param $userTokenInfo
     * @return void
     */
    public function skuSearch($data){
        $goods_id = $data['goods_id'];
        $spec_id = json_decode($data['spec_id'],true);
        $where = "gs.goods_id=$goods_id and gs.is_delete=0";
        if(!empty($spec_id) && is_array($spec_id)){
            foreach ($spec_id as $k=>$v){
                $where .= " and JSON_CONTAINS(gs.spec_info,JSON_OBJECT($k, $v))";
            }
        }
        $conn = new Conn();
        $商品SKU信息 = "select sku_id,gs.goods_id,sku_code,sku_name,sku_img_id,sku_stock,sku_old_price,sku_sell_price from shop_goods_sku as gs inner join shop_goods as g on gs.goods_id=g.goods_id where $where";
        $商品SKU信息 = $conn->readConn($商品SKU信息);
        $商品SKU信息["sku_sell_price"] = round($商品SKU信息["sku_sell_price"] / CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"],2)."";
        $商品SKU信息["sku_linglong_price"] = $商品SKU信息["sku_sell_price"];
        if(!$商品SKU信息) Result::success();

        $图片信息 = $conn->readConn("select file_id,storage,`domain`,file_path from jj_file where file_id={$商品SKU信息['sku_img_id']} limit 1");
        $商品SKU信息['sku_img_url'] = Common::fileUrl($图片信息);
        $商品SKU信息['spec_name'] = '';
        if(!empty($spec_id) && is_array($spec_id)){
            $规格ID = implode(',',$spec_id);
            $商品规格信息 = $conn->readConn("select spec_id,name from shop_goods_spec where spec_id in($规格ID)",true);
            $商品规格信息 = implode(',',array_column($商品规格信息,'name'));
            $商品SKU信息['spec_name'] = $商品规格信息;
        }
        Result::success($商品SKU信息);
    }
}